package com.bbs.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;
import com.bbs.beans.Submit;

import manager.PersistentManager;
import manager.Utils;

/**
 * 发表帖子 Servlet implementation class SendTieZi
 * 上传的upload中要有subjectid
 */
// @WebServlet("/SendTieZi")
public class SendTieZi extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SendTieZi() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// response.getWriter().append("Served at:
		// ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
		Session session = sf.openSession();
		
		String data = request.getParameter("data");
		Upload upload = JSON.parseObject(data, Upload.class);
		Download download = new Download();

		Transaction tx = session.beginTransaction();

		try {
			Submit submit = upload.getSubmit();
			submit.setCommitbackcount(0);
			//submit.setTime(Calendar.getInstance());
			submit.setChangeTime(Utils.currentTime());
			session.save(submit);
			tx.commit();
			download.setStatus(DownloadInfo.SUCCESS);
		} catch (Exception e) {
			download.setStatus(DownloadInfo.FAILED);
			tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		
		System.out.println(JSON.toJSONString(download));
		response.getWriter().append(JSON.toJSONString(download));

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	// 上行
	public static class Upload {
		// 主题id
		@Deprecated
		Long subjectId;

		// 帖子内容
		Submit submit;

		public Long getSubjectId() {
			return subjectId;
		}

		public void setSubjectId(Long subjectId) {
			this.subjectId = subjectId;
		}

		public Submit getSubmit() {
			return submit;
		}

		public void setSubmit(Submit submit) {
			this.submit = submit;
		}

	}

	// 下行数据
	public static class Download {
		// 状态
		int status;

		public int getStatus() {
			return status;
		}

		public void setStatus(int status) {
			this.status = status;
		}

	}

}
